import React, { Component } from 'react';
import { View, Text, TouchableOpacity, Switch, StyleSheet, Alert, ScrollView, TextInput,Dimensions } from 'react-native';
import { List, InputItem, Flex, DatePicker, Toast } from 'antd-mobile-rn';
import Icon from '../home/icon/iconfont';
import constants from '../../utils/constants';
import moment from 'moment';
import api from '../../utils/api';

const window = Dimensions.get("window");

const styles = StyleSheet.create({
    rtime: {
        width: 60,
        height: 30,
        backgroundColor: "#ddd",
        alignItems: "center",
        justifyContent: "center",
        marginRight: 10,
        marginBottom: 10
    }
})


const ShowDateComponent = ({ extra, onClick, children }) => (
    <TouchableOpacity activeOpacity={0.6} onPress={onClick}>
        {children}
    </TouchableOpacity>
);


export default class TaskEdit extends Component {


    static navigationOptions = (e) => {

        const { state } = e.navigation;

        const onSaveClick = () => {

            state.params.onSaveClick();

        }

        return {
            headerTintColor: 'black',
            headerBackTitle: null,
            headerStyle: {
                backgroundColor: '#ffffff',
                borderBottomWidth: 0,
                shadowOpacity: 0,
                elevation: 0,
            },
            headerRight: (
                <Text onPress={onSaveClick} style={{ marginRight: 20, fontSize: 18, color: "#000", fontWeight: "300" }}>保存</Text>
            )
        }
    }

    constructor(props) {
        super(props);
        const { navigation } = this.props;
        this.state = {
            phone: "",
            frequencys: {
                "周一": 1,
                "周二": 2,
                "周三": 3,
                "周四": 4,
                "周五": 5,
                "周六": 6,
                "周日": 7
            },
            task: {
                title: navigation.getParam("name"),
                startDate: new Date(),
                endDate: moment(new Date()).add(7, "day").toDate(),
                remainTimes: [
                    "09:00"
                ]
            },
            checked: true
        }


    }


    onShowTimer = () => {

    }

    componentDidMount() {
        const { navigation } = this.props;
        const isEdit = navigation.getParam("isEdit");
        navigation.setParams({
            onSaveClick: () => {


                const { task, frequencys } = this.state;
                if (!task.title) {
                    Toast.info("请输入学习任务");
                    return;
                }

                Alert.alert("提示", "是否保存", [
                    { text: "取消" },
                    {
                        text: "确认", onPress: () => {
                            Toast.loading("保存中...", 0);
                            api({
                                url: isEdit ? "/task/update" : "/task/create",
                                method: isEdit ? "POST" : "PUT",
                                body: {
                                    taskId: navigation.getParam("taskId"),
                                    taskName: task.title,
                                    startDate: task.startDate.getTime(),
                                    endDate: task.endDate.getTime(),
                                    remainWeek: Object.keys(frequencys).map(key => frequencys[key]).filter(value => value != "").join(","),
                                    remainTime: task.remainTimes.join(",")

                                }
                            }).then(data => {
                                if (!data.success) {
                                    Toast.info(data.msg);
                                    return;
                                }
                                Toast.info("保存成功", 1.5);
                                const back = navigation.getParam("back");
                                if (back) {
                                    back();
                                }
                                navigation.navigate("Home");

                            }).catch(data => {
                                Toast.info("保存失败,请重试");
                            })
                        }
                    }
                ])



            }
        })

        if (navigation.getParam("isEdit")) {
            const taskId = navigation.getParam("taskId");
            api({
                url: `/task/info?taskId=${taskId}`,
                method: "POST"
            }).then(data => {
                if (!data.success) {
                    Toast.info("获取任务详情失败");
                    navigation.goBack();
                    return;
                }
                const vo = data.result;
                const frequencys = {};
                if (vo.remainWeek) {
                    vo.remainWeek.split(",").forEach(value => {

                        if (value == 1) {
                            frequencys["周一"] = 1;
                        }
                        if (value == 2) {
                            frequencys["周二"] = 2;
                        }
                        if (value == 3) {
                            frequencys["周三"] = 3;
                        }
                        if (value == 4) {
                            frequencys["周四"] = 4;
                        }
                        if (value == 5) {
                            frequencys["周五"] = 5;
                        }
                        if (value == 6) {
                            frequencys["周六"] = 6;
                        }
                        if (value == 7) {
                            frequencys["周日"] = 7;
                        }
                    });
                }

                this.setState({
                    task: {
                        title: vo.taskName,
                        startDate: new Date(vo.startDate),
                        endDate: new Date(vo.endDate),
                        remainTimes: vo.remainTime ? vo.remainTime.split(",") : []
                    },
                    checked: vo.isRemain === 1,
                    frequencys: frequencys
                })
            }).catch(() => {
                Toast.info("获取任务详情失败");
                navigation.goBack();
            })
        }
    }

    render() {


        const { task } = this.state;

        const remainTimes = this.state.checked ? (
            <View style={{ flexDirection: "row", flexWrap: 'wrap', }}>

                <DatePicker
                    mode={"time"}
                    title={"提醒时间"}
                    onChange={(value) => {
                        const date = moment(value).format("HH:mm");
                        if (task.remainTimes.filter(text => text === date).length > 0) {
                            Toast.info("已选择该时间");
                            return;
                        }

                        task.remainTimes.push(moment(value).format("HH:mm"));
                        this.setState({
                            task: task
                        })
                    }}
                >
                    <ShowDateComponent>
                        <View style={styles.rtime}>
                            <Icon name={"iconfontadd"} size={20}></Icon>
                        </View>
                    </ShowDateComponent>
                </DatePicker>
                {
                    task.remainTimes.map((text, index) => {
                        return (
                            <TouchableOpacity activeOpacit={0.5} key={index} onLongPress={() => {
                                Alert.alert("是否删除", "", [
                                    { text: "取消" },
                                    {
                                        text: "确认", onPress: () => {
                                            task.remainTimes.splice(index, 1);
                                            this.setState({
                                                task: task
                                            })
                                        }
                                    }
                                ])
                            }}>
                                <View style={styles.rtime}>
                                    <Text>{text}</Text>
                                </View>
                            </TouchableOpacity>

                        )
                    })
                }
            </View>
        ) : undefined;

        return (

            <View style={{ flex: 1 }}>
                <ScrollView>


                    <List>
                        {/* <InputItem
                            clear
                            labelNumber={3}
                            value={task.title}
                            placeholder={"输入学习任务"}
                            onChange={(value) => {
                                task.title = value;
                                this.setState({
                                    task: task
                                });
                            }}

                            onBlur={() => {
                                this.setState({ otherLoginView: "none" })
                            }}

                        >
                            <Icon name={"ceshishenqing"} size={32}></Icon>
                        </InputItem> */}
                        <List.Item>
                            <View style={{ flexDirection: "row",marginTop:5,marginBottom:5 }}>
                                <View style={{width:35,flexDirection:"row"}}>
                                    <Icon name={"ceshishenqing"} size={32}></Icon>
                                </View>

                                <TextInput value={task.title} onChange={(e)=>{
                                    task.title = e.nativeEvent.text;
                                    this.setState({
                                        task:task
                                    })
                                }} returnKeyType={"done"} clearButtonMode={"always"} placeholder={"输入学习任务"} style={{ borderWidth: 0, marginLeft: 15, width: window.width -80 }}></TextInput>
                            </View>
                        </List.Item>
                        <List.Item>
                            <Flex style={{ marginBottom: 15, marginTop: 5 }}>

                                <Flex.Item>
                                    <Text style={{ fontSize: 14 }}>起始时间</Text>
                                </Flex.Item>
                                <Flex.Item>
                                    <Text style={{ marginLeft: 20, fontSize: 14 }}>结束时间</Text>
                                </Flex.Item>
                            </Flex>
                            <View style={{ flexDirection: "row", marginBottom: 15 }}>
                                <DatePicker
                                    title={"开始时间"}
                                    format={"YYYY年MM月DD日"}
                                    value={task.startDate}
                                    mode="date"
                                    minDate={new Date()}
                                    onChange={(value => {
                                        task.startDate = value;
                                        if (value.getTime() >= task.endDate.getTime()) {
                                            task.endDate = moment(value).add(7, "day").toDate();
                                        }
                                        this.setState({
                                            task: task
                                        })
                                    })}
                                >
                                    <ShowDateComponent>
                                        <Text style={{ fontSize: 18, color: "#000" }}>{moment(task.startDate).format("YYYY年MM月DD日")}</Text>
                                    </ShowDateComponent>
                                </DatePicker>

                                <View style={{ height: 2, backgroundColor: constants.themeColor, width: 30, marginLeft: 20, marginTop: 12 }}></View>
                                <DatePicker
                                    title={"结束时间"}
                                    format={"YYYY年MM月DD日"}
                                    value={task.endDate}
                                    mode="date"
                                    minDate={task.startDate
                                    }
                                    onChange={(value => {
                                        task.endDate = value;
                                        this.setState({
                                            task: task
                                        })
                                    })}
                                >
                                    <ShowDateComponent>
                                        <Text style={{ fontSize: 18, color: "#000", marginLeft: 15 }}>{moment(task.endDate).format("YYYY年MM月DD日")}</Text>
                                    </ShowDateComponent>
                                </DatePicker>
                            </View>
                        </List.Item>
                        <List.Item>
                            <View style={{ flexDirection: "row", marginTop: 5, marginBottom: 15 }}>
                                <Icon name={"duihuan"} size={32}></Icon>
                                <Text style={{ marginLeft: 15, marginTop: 10 }}>频率</Text>
                            </View>
                            <Flex style={{ marginBottom: 15 }}>
                                {
                                    [
                                        { title: "周一", value: 1 },
                                        { title: "周二", value: 2 },
                                        { title: "周三", value: 3 },
                                        { title: "周四", value: 4 },
                                        { title: "周五", value: 5 },
                                        { title: "周六", value: 6 },
                                        { title: "周日", value: 7 }
                                    ].map((item, index) => {
                                        const frequencys = this.state.frequencys;
                                        const d = frequencys[item.title];
                                        const isSelected = (d != null && d != undefined);
                                        return (
                                            <Flex.Item key={index} style={{ alignContent: "center", alignItems: "center" }}>
                                                <TouchableOpacity activeOpacity={0.5} onPress={() => {
                                                    const frequencys = this.state.frequencys;
                                                    if (frequencys[item.title]) {
                                                        frequencys[item.title] = null;
                                                    } else {
                                                        frequencys[item.title] = item.value;
                                                    }
                                                    this.setState({
                                                        frequencys: frequencys
                                                    })

                                                }}>
                                                    <View style={{ padding: 8, backgroundColor: isSelected ? constants.themeColor : "#ccc", borderRadius: 5 }}>
                                                        <Text style={{ color: isSelected ? "#fff" : "#666" }}>{item.title}</Text>
                                                    </View>
                                                </TouchableOpacity>
                                            </Flex.Item>
                                        )
                                    })
                                }

                            </Flex>
                        </List.Item>
                        <List.Item>
                            <View style={{ flexDirection: "row", marginTop: 5, marginBottom: this.state.checked ? 15 : 0, position: "relative", width: "100%" }}>
                                <Icon name={"taskmanagement"} size={32}></Icon>
                                <Text style={{ marginLeft: 15, marginTop: 10 }}>提醒</Text>
                                <View style={{ position: "absolute", right: 0 }}>
                                    <Switch value={this.state.checked} trackColor={{ true: constants.themeColor }} onValueChange={() => {
                                        this.setState({
                                            checked: !this.state.checked
                                        })
                                    }}></Switch>
                                </View>
                            </View>
                            {remainTimes}
                        </List.Item>
                    </List>
                </ScrollView>
            </View>
        )

    }
}